package controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import connection.ServiceProxy;

/**
 * Servlet implementation class UpdateMyAdvertisement
 */
public class UpdateMyAdvertisement extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpdateMyAdvertisement() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
			
		String message = null, result = null, destination = "/ViewMyAdvertisement";
		String itemId =  request.getParameter("itemId");
		
		
		boolean error = false;
		String itemQuantity = request.getParameter("itemQuantity");
		
		ServiceProxy oProxy = new ServiceProxy();
		
		if(null != itemId) {
			
			if(request.getParameter("submit").equals("Delete")){
				result = oProxy.deleteMyAdvertisement(itemId);
				if(result.equals("true"))
					message = "Item Deleted Successfully";
				else if(result.equals("false")){
					message = "Item Cannot be deleted. Purchased by other user";
				}
				else
					message="Please try again";
			}
			else if(request.getParameter("submit").equals("Update")){
			//int ite
				System.out.println("Update Enetered");
				if(request.getParameter("itemQuantity").equals("")) {
					error = true;
					message = "Invalid Quantity";
				}				
				
				if(error == false) {
					try {
						Integer.parseInt(itemQuantity);
					}
					catch(NumberFormatException e) {
						error = true;
						message = "Please enter correct value of quantity";
					}
				}
				
							
				if(error == false) {
					
					result = oProxy.updateMyAdvertisement(itemId,"" + itemQuantity);
					System.out.println("Result" + result);
					if(result.equals("true")) {
						message = "Item Updated Successfully";					
					}
					else {
						error = true;
						message = "Please try again";
					}
						
				}
			}	
		}
		
		request.setAttribute("message", message);
		RequestDispatcher rd = this.getServletContext().getRequestDispatcher(destination);
		rd.forward(request, response);
	}

}
